package com.richapp.launcher.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.richapp.launcher.R;
import com.richapp.launcher.common.AdvType;
import com.richapp.launcher.dao.adv.Adv;
import com.richapp.launcher.service.AdvService;
import com.richapp.launcher.ui.activities.ScreenSaverAdvActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 屏保
 * Created by yif on 16/7/31.
 */
public class ScreenSaverPicView extends View {

    private static final String TAG = ScreenSaverPicView.class.getName();

    public static volatile Boolean needUpdateResources = false;

    public final String PATH_ADV_FILE = getContext().getFilesDir() + File.separator + "adv";

    int COMPONENT_WIDTH;//控件的宽度

    int COMPONENT_HEIGHT;//控件的高度  

    boolean initflag = false;//是不是已经初始化图片  

    List<Bitmap> bitmaps = new ArrayList<Bitmap>();

    int currPicIndex = -1;//以后播放图片的ID

    boolean workFlag = true;//播放图片的线程标识位


    List<Adv> advs = AdvService.advMap.get(AdvType.SCREEN_SAVER_TYPE);

    private List<Integer> defaultScreenSaverAdvs = Arrays.asList(R.drawable.screen_saver_0, R.drawable.screen_saver_1, R.drawable.screen_saver_2, R.drawable.screen_saver_3);


    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public ScreenSaverPicView(Context father, AttributeSet as) {

        super(father);

        initBitmap();//图片初始化终了

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (workFlag && !ScreenSaverAdvActivity.finished) {
                    try {
                        if (needUpdateResources) {
                            initBitmap();
                            needUpdateResources = false;
                        }

                        if (bitmaps.size() > 0) {
                            currPicIndex = (currPicIndex + 1) % bitmaps.size();//变动图片的ID
                            ScreenSaverPicView.this.postInvalidate();//刷新屏幕，导致屏幕重绘
                            if (currPicIndex < advs.size()) { //说明是下载的广告资源,需要上报播放
                                AdvService.playedAdvs.offer(advs.get(currPicIndex));
                            }
                        }
                        try {
                            Thread.sleep(5000);//每隔5秒钟刷新屏幕一次
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "播放图片失败", e);
                    }
                }
            }
        });

    }

    //初始化图片  
    public void initBitmap() {

        bitmaps.clear();

        BitmapFactory.Options options = new BitmapFactory.Options();

        advs = AdvService.advMap.get(AdvType.SCREEN_SAVER_TYPE);

        Log.e(TAG, "广告数量: " + advs.size() + "\t" + advs.toString());
        for (Adv adv : advs) {
            String id = adv.getId();
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(PATH_ADV_FILE + File.separator + id, options);
                if (bitmap != null)
                    bitmaps.add(bitmap);
            } catch (Exception e) {
                Log.e(TAG, "加载图片失败 id=" + id, e);
            }
        }

        Log.e(TAG, "加载广告数量: " + bitmaps.size());

        int size = 4 - bitmaps.size();
        for (int i = 0; i < size; i++) { //加载默认资源,从0到size-1
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), defaultScreenSaverAdvs.get(i), options);
            bitmaps.add(bitmap);
        }
        Log.e(TAG, "加载图片数量: " + bitmaps.size());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!initflag)//检查是偶已经获得控件的宽和高，如果没有，那么就获得控件的宽和高  
        {
            COMPONENT_WIDTH = this.getWidth();
            COMPONENT_HEIGHT = this.getHeight();
            initflag = true;
        }
        RectF rectF = new RectF(0, 0, COMPONENT_WIDTH, COMPONENT_HEIGHT);
        canvas.drawBitmap(bitmaps.get(currPicIndex), null, rectF, null);//绘制图片
    }
}
